import {ApiResponse} from "@/entiy/vo/ApiResponse.ts";
import {BizResult} from "@/entiy/vo/BizResult.ts";

export class BizResultUtils {

    /**
     * 判断是否是错误结果
     *
     * @param bizResult 传入的业务结果
     */
    public static isError<T>(bizResult: BizResult<T>): boolean {
        if (bizResult === undefined || bizResult === null) {
            console.log("BizResult is null or undefined");
            return true;
        }

        const bizCode = bizResult.bizCode
        if (bizCode === undefined || bizCode === null) {
            console.log("BizCode is null or undefined");
            return true;
        }

        return bizResult.bizCode !== 0;
    }

    /**
     * 判断响应是否是错误结果
     *
     * @param response 传入的响应结果
     */
    public static isResponseError<T>(response: ApiResponse<T>): boolean {
        if (response === undefined || response === null) {
            console.log("ApiResponse is null or undefined");
            return true;
        }

        const code = response.code;
        if (code === undefined || code === null) {
            console.log("ApiResponse code is null or undefined");
            return true;
        }

        return code !== 0;
    }

    /**
     * 处理接口的返回结果
     *
     * @param response 传入的响应结果
     */
    public static handleResult<T>(response: ApiResponse<T>): BizResult {
        const isError = this.isResponseError(response);
        if (response === undefined || response === null) {
            console.log("AxiosResponse is null or undefined");
            return this.systemError();
        }

        if (isError) {
            return this.requestFailed(response);
        } else {
            return this.requestSuccess(response);
        }
    }

    /**
     * 返回请求成功的结果
     *
     * @param response 传入的响应结果
     */
    public static requestSuccess<T>(response: ApiResponse<T>): BizResult<T> {
        return {
            bizData: response.data,
            bizCode: response.code,
            errorMsg: response.msg
        }
    }

    /**
     * 返回请求失败的结果
     *
     * @param response  传入的响应结果
     */
    public static requestFailed<T>(response: ApiResponse<T>): BizResult<T> {
        return {
            bizData: response.data,
            bizCode: response.code,
            errorMsg: response.msg
        }
    }

    /**
     * 返回系统错误的结果
     */
    public static systemError(): BizResult {
        return {
            bizData: null,
            bizCode: -1,
            errorMsg: "系统繁忙, 请稍后再尝试!"
        };
    }
}
